<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/bootstrap/bootstrap.min.css"/>
    <link rel="stylesheet" href="/layui/css/layui.css"  media="all">
    <link rel="stylesheet" href="/ztree/css/ztree-bootstrap.css"/>
    <script src="/jquery/jquery.min.js"></script>
    <script src="/layer/layer.js"></script>
    <script src="/ztree/js/jquery.ztree.core.js"></script>
    <script src="/ztree/js/jquery.ztree.excheck.js"></script>
    <script src="/ztree/js/jquery.ztree.exedit.js"></script>
</head>

<style>
    .searchdiv{
        background: #fff;
        border-radius: 6px;margin-top: 10px;
        box-shadow: 1px 1px 3px rgba(0,0,0,.2);
        padding: 10px;
    }
</style>

<body style="background-color: #f3f3f4;">


<div class="searchdiv">
        <div class="layui-row layui-form-item">
            <div class="layui-col-xs6">
                <label class="layui-form-label" style="width: 100px;">权限名：</label>
                <div class="layui-input-block">
                    <input type="text" name="rolename" lay-verify="required" placeholder="" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-col-xs3" style="padding-left:20px; ">
                <button type="button" class="layui-btn" id="btn_query">查询</button>
            </div>
        </div>
</div>

    <div class="searchdiv">
        <button class="layui-btn layui-btn-normal" id="addRole">新增</button>
        <table class="layui-hide" id="test" lay-filter="test"></table>
    </div>

<div id="tyes" style="display: none">

</div>

<div id="addRoleForm" style="display: none">
    <form class="layui-form"  id="addrolelForm" style="padding: 20px;" action="">
        <div class="layui-form-item">
            <label class="layui-form-label">角色名称 :</label>
            <div class="layui-input-block">
                <input type="text" name="name"  lay-verify="required" placeholder="请输入"  class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">角色描述 :</label>
            <div class="layui-input-block">
                <input type="text" name="description" placeholder="请输入"  class="layui-input">
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit="" lay-filter="addSubmit">立即提交</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </form>

</div>
<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-xs" lay-event="roleList">编辑权限</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<script src="/layui/layui.all.js" charset="utf-8"></script>


<script>

    ;!function(){
        var table = layui.table;
        var $ = layui.jquery,layer = layui.layer;
        var form = layui.form;

        var editwindow ;

        //第一个实例
        var tableIns = table.render({
            elem: '#test'
            ,height: 312
            ,where: {}
            ,url: '/role/list' //数据接口
            ,page: true //开启分页
            ,cols: [
                [ //表头
                    {field: 'id', title: 'ID', sort: true, fixed: 'left'}
                    ,{field: 'name', title: '角色名称',align:'center'}
                    ,{field: 'description', title: '角色描述', sort: true}
                    ,{field: 'status', title: '用户状态',templet: function(d){
                        if(d.status ==1){
                            return "有效";
                        }else{
                            return "无效";
                        }
                    }}
                    ,{field: 'createTime', title: '创建时间'}
                    ,{field: 'updateTime', title: '修改时间'}
                    ,{fixed: 'right', title:'操作', width:230, toolbar: '#barDemo'}
                ]
            ]
        });


        /**
         * 查询按钮
         **/

        $("#btn_query").click(function(){
            tableIns.reload({
                where:{
                    rolename:$("input[name=rolename]").val()

                },page: {
                    curr: 1 //重新从第 1 页开始
                }
            })
        });

        //监听表格行工具事件
        table.on('tool(test)', function(obj){
            var data = obj.data;
            //console.log(obj)
            if(obj.event === 'del'){
                parent.layer.confirm('真的删除行么', function(index){
                    $.ajax({
                        url:"/role/del",
                        type:"post",
                        data:{roleId:data.id},
                        success:function(data){
                            if(data.ret){
                                obj.del();
                                parent.layer.close(index);
                                parent.layer.msg("删除成功!")
                            }
                        }
                    })

                });
            }
            else if(obj.event === 'edit'){
                $("#tyes").load("/role/edit?id=" + data.id,function(response,status,xhr){
                    if (status=="success"){

                        editwindow = parent.layer.open({
                            type: 1,
                            area: ['500px', '420px'],
                            content: $('#tyes').html(),
                            success:function(){
                                parent.layui.form.render();
                            }
                        });

                    }
                });
            }
            else if(obj.event === 'roleList'){
                window.onloadRole(obj.data.id);

            }
        });

        /**
         *  监听编辑用户的提交表单事件
         */
        parent.layui.form.on('submit(editSubmit)', function(data){
            $.ajax({
                url:"/role/edit",
                type:"post",
                dataType:"json",
                data:parent.$("#roleDetailForm").serialize(),
                success:function(data){
                    if(data.ret){
                        parent.layer.close(editwindow);
                        parent.layer.msg("修改成功!");
                        tableIns.reload({
                            where: {}
                            ,page: {
                                curr: 1 //重新从第 1 页开始
                            }
                        });
                    }
                }
            })


            return false;
        });

        /**
         *  新增按钮 单击事件 打开模态框
         * */
        var addwindow ;
        $("#addRole").click(function(){
            addwindow = parent.layer.open({
                type: 1,
                area: ['500px', '300px'],
                content: $('#addRoleForm').html(),
                success:function(){
                    parent.layui.form.render();
                }
            });
        });

        /**
         * 监听新增角色的提交按钮事件
         * */
        parent.layui.form.on('submit(addSubmit)',function(data){
            $.ajax({
                url:"/role/add",
                dataType:"json",
                type:"post",
                data:parent.$("#addrolelForm").serialize(),
                success:function(data){
                    if(data.ret){
                        parent.layer.msg("添加成功!");
                        parent.layer.close(addwindow);
                        /* 重载数据表格从第一页开始*/
                        tableIns.reload({where:{},page: {curr: 1 }})
                    }else{
                        parent.layer.msg("添加失败");
                    }
                },error:function(data){
                    parent.layer.close(addwindow);
                    parent.layer.msg("系统错误");
                }
            })
            return false;
        })
    }();

    /**
     * 编辑权限js
     * @param id
     */
    function onloadRole(id) {
        $.ajax({
            url: "/role/permissionlistByroleId",
            dataType: "json",
            data: {
                "roleId": id
            }, success: function (data) {
                if (data.ret) {
                    //树-初始化设置
                    var treeSetting = {
                        check: {
                            enable: true
                        },
                        data: {
                            simpleData: {
                                enable: true,
                                idKey: "id",
                                pIdKey: "pid",
                                rootPId: 0
                            }
                        }
                    };
                    var treeObj = parent.$.fn.zTree.init(parent.$("#roleTree"), treeSetting, data.data);
                    fillter(treeObj);//设置展开前三级
                    parent.$("#saveRole").click(function () {
                        var permissionid = [];
                        for (var role in treeObj.getCheckedNodes()) {
                            permissionid.push(treeObj.getCheckedNodes()[role].permissionId)
                        }

                        $.ajax({
                            type: "post",
                            url: "/role/updateRoleIdbyPermissionId",
                            dataType: "json",
                            traditional: true,
                            data: {
                                  "roleid": id // userid
                                , "permissionid": permissionid //roleId []...
                            }, success: function (data) {
                                if (data.ret) {
                                    parent.layer.msg("修改成功!");
                                    parent.layer.close(index);
                                }
                            }
                        })
                        parent.$("#UserRoleList").hide();

                    })

                    var index = parent.layer.open({
                        type: 1,
                        area: ['800px', '500px'],
                        content: parent.$('#UserRoleList') //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                        ,end : function(){
                            parent.$('#UserRoleList').hide();
                        }
                    });
                }
            }
        });


    }

    /**
     * 设置树的层级 js
     * @param treeObj
     */
    function fillter(treeObj) {
        //获得树形图对象
        var nodeList = treeObj.getNodes();　　　　　　
        for(var i = 0; i < nodeList.length; i++) { //设置节点展开第二级节点
            treeObj.expandNode(nodeList[i], true, false, true);
            // var nodespan = nodeList[i].children;
            // for(var j = 0; j < nodespan.length; j++) { //设置节点展开第三级节点
            //     treeObj.expandNode(nodespan[j], true, false, true);
            // }
        }
    }

</script>



</body>

</html>
